"""
GitHub Trending 路由
"""

from flask import Blueprint, jsonify, request
import sys
import os
from datetime import datetime

# 添加路径 - 定位到项目根目录的 tools 文件夹
# 在 Docker 容器中: /app/routes/github_trending.py -> /app
# 在本地开发中: apps/backend/routes/github_trending.py -> project_root
current_file = os.path.abspath(__file__)
routes_dir = os.path.dirname(current_file)
backend_or_app_dir = os.path.dirname(routes_dir)

# 检查是否在 Docker 容器中（/app）或本地开发环境
if os.path.basename(backend_or_app_dir) == 'app':
    # Docker 容器环境: /app
    project_root = backend_or_app_dir
else:
    # 本地开发环境: apps/backend -> project_root
    project_root = os.path.dirname(os.path.dirname(backend_or_app_dir))

scraper_path = os.path.join(project_root, 'tools', 'github_trending_scraper')
sys.path.insert(0, scraper_path)

from github_trending_scraper import GitHubTrendingScraper
from cache_manager import CacheManager

bp = Blueprint('github_trending', __name__)
scraper = GitHubTrendingScraper()
cache = CacheManager()

@bp.route('/trending', methods=['GET'])
def get_trending():
    """
    获取 GitHub Trending 数据
    
    查询参数:
    - language: 编程语言 (可选)
    - since: 时间范围 (daily/weekly/monthly，默认: daily)
    - limit: 返回数量 (默认: 50)
    - force: 强制刷新 (true/false，默认: false)
    """
    try:
        language = request.args.get('language', '')
        since = request.args.get('since', 'daily')
        limit = int(request.args.get('limit', 50))
        force = request.args.get('force', 'false').lower() == 'true'
        
        # 生成缓存键
        cache_key = f"trending_{language or 'all'}_{since}_{limit}"
        
        # 如果不是强制刷新，尝试从缓存获取
        if not force:
            cached_data = cache.get(cache_key, max_age_hours=4)
            if cached_data:
                return jsonify({
                    'success': True,
                    'data': cached_data['data'],
                    'count': len(cached_data['data']),
                    'filters': {
                        'language': language or 'all',
                        'since': since,
                        'limit': limit
                    },
                    'cached': True,
                    'cached_at': cached_data['cached_at']
                })
        
        # 爬取新数据
        print(f"正在爬取: {cache_key}")
        repos = scraper.scrape_trending_repos(language=language, since=since, limit=limit)
        
        # 保存到缓存
        cache.set(cache_key, repos)
        
        return jsonify({
            'success': True,
            'data': repos,
            'count': len(repos),
            'filters': {
                'language': language or 'all',
                'since': since,
                'limit': limit
            },
            'cached': False,
            'cached_at': datetime.now().isoformat()
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@bp.route('/languages', methods=['GET'])
def get_languages():
    """获取支持的编程语言列表"""
    languages = [
        {'value': '', 'label': '全部语言'},
        {'value': 'javascript', 'label': 'JavaScript'},
        {'value': 'typescript', 'label': 'TypeScript'},
        {'value': 'python', 'label': 'Python'},
        {'value': 'java', 'label': 'Java'},
        {'value': 'go', 'label': 'Go'},
        {'value': 'rust', 'label': 'Rust'},
        {'value': 'c++', 'label': 'C++'},
        {'value': 'c#', 'label': 'C#'},
        {'value': 'php', 'label': 'PHP'},
        {'value': 'ruby', 'label': 'Ruby'},
        {'value': 'swift', 'label': 'Swift'},
        {'value': 'kotlin', 'label': 'Kotlin'},
        {'value': 'vue', 'label': 'Vue'},
    ]
    return jsonify({
        'success': True,
        'data': languages
    })

